/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.util;

import java.io.ByteArrayInputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;

/**
 * This class implements an audio input stream that plays a "beep"
 * (sine wave of given frequency and duration).
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
public final class Beep extends AudioInputStream {

    /** Sample size in bits. */
    private static final int SAMPLE_SIZE_IN_BITS = 16;

    /** Number of channels. */
    private static final int CHANNELS = 2;

    /** Frame size in bytes. */
    private static final int FRAME_SIZE = 4;

    /** Little-endian value. */
    private static final boolean LITTLE_ENDIAN = false;

    /** Sound volume. */
    private static final float VOLUME = 0.7f;

    /** Mask for byte values. */
    private static final int BYTE_MASK = 0xFF;

    /** Size of byte values. */
    private static final int BYTE_SIZE = 8;

    /** Number of milliseconds per second. */
    private static final long MILLISECS_PER_SEC = 1000L;

    /**
     * Creates an audio input stream that plays a "beep".
     * @param sampleRate stream sample rate (number of samples per second)
     * @param frequency beep frequency (in Hz)
     * @param duration beep duration (in milliseconds)
     */
    public Beep(final float sampleRate,
                final float frequency,
                final long duration) {
        super(new ByteArrayInputStream(createData(sampleRate,
                                                  frequency,
                                                  duration)),
              new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                              sampleRate,
                              Beep.SAMPLE_SIZE_IN_BITS,
                              Beep.CHANNELS,
                              Beep.FRAME_SIZE,
                              sampleRate,
                              Beep.LITTLE_ENDIAN),
              AudioSystem.NOT_SPECIFIED);
    } // end constructor(float, float, long)

    /**
     * Creates data for the audio stream.
     * @param sampleRate stream sample rate (number of samples per second)
     *                    - should be > 0.0f
     * @param frequency beep frequency (in Hz) - should be > 0.0f
     * @param duration beep duration (in milliseconds) - should be > 0
     * @return data for a sinus wave matching the parameters
     */
    private static byte[] createData(final float sampleRate,
                                     final float frequency,
                                     final long duration) {
        assert sampleRate > 0.0f : "sampleRate should be > 0.0f";
        assert frequency > 0.0f : "frequency should be > 0.0f";
        assert duration > 0 : "duration should be > 0";
        final float amplitude =
            Beep.VOLUME * (float) Math.pow(2, Beep.SAMPLE_SIZE_IN_BITS - 1);
        final int periodLengthInFrames = Math.round(sampleRate / frequency);
        final int bufferLength =
            Math.round((sampleRate * duration) / Beep.MILLISECS_PER_SEC) * Beep.FRAME_SIZE;
        final byte[] res = new byte[bufferLength];
        final int len = bufferLength / Beep.FRAME_SIZE;
        for (int frame = 0; frame < len; frame++) {
            final float periodPosition = (float) (frame % periodLengthInFrames)
                / (float) periodLengthInFrames;
            final float value =
                (float) Math.sin(periodPosition * 2.0 * Math.PI);
            final int val = Math.round(value * amplitude);
            // 16-bit stereo, little endian
            final int addr = frame * Beep.FRAME_SIZE;
            final byte low = (byte) (val & Beep.BYTE_MASK);
            final byte high = (byte) ((val >>> Beep.BYTE_SIZE) & Beep.BYTE_MASK);
            res[addr + 0] = low;
            res[addr + 1] = high;
            res[addr + 2] = low;
            res[addr + 3] = high;
        } // end for
        return res;
    } // end method 'createData(float, float, long)'

} // end class 'Beep'
